<?php
/**
 * 资讯分类
 * User: 江玉婵（QQ:1129901500)
 * Date: 2017/7/7
 * Time: 10:28
 */
namespace app\admin\controller;

use think\Controller;
use app\admin\model\NewsCate as NewsCate_mod;
use think\Config;
use think\Session;

class NewsCate extends Base{

    //这个方法没执行
    public function _initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::_initialize();
        //TODO:自定义的初始化
        $this->mod = new NewsCate_mod();
        $this->assign('title','资讯分类');
    }

    public function index() {
        $keyword = trim ($this->request->param('keyword'));

        $field = 't.id,t.name,t.utime,a.name as uadmin';
        $where = ['t.is_work'=>1];
        $order = ['t.id' => 'desc'];
        $join = [['admin a','a.id = t.uadmin','left']];

        if (! empty ( $keyword )) {
            $where['t.name'] = ['like',"%$keyword%"];
        }

        $list = $this->mod->field($field)->where($where)->order($order)->alias('t')->join($join)->paginate(10);

        $this->assign ( ['list' => $list, 'keyword' => $keyword]);
        unset($list);
        return view();
    }

    public function edit() {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $data['utime'] = date('Y-m-d H:i:s');
            $data['uadmin'] = $this->session_id;
            if ( !isset($data['id']) ) {
                $data['ctime'] = date('Y-m-d H:i:s');
                $data['cadmin'] = $this->session_id;
                $this->mod->data($data)->save();
            } else {
                $where['id'] = $data['id'];
                unset($data['id']);
                $this->mod->save($data,$where);
            }
            $this->success('保存成功','NewsCate/index');
        } else {
            $cate = $this->getInfo(); // 顶级分类

            $id = $this->request->param('id');
            $where['is_work'] = 1;
            $order['id'] = 'desc';
            if ($id) {
                $where['id'] = $id;
                $row = $this->mod->field('id,pid,name')->where($where)->order($order)->find();
                unset($where['id']);

                $this->assign(['row'=>$row, 'cate' => $cate]);
                return view();
            } else {
                $this->assign(['cate' => $cate]);
                return view('add');
            }
        }
    }

    public function getInfo($field='id,name') {
        $where ['is_work'] = 1;
        $list_pre = $this->mod->field($field)->where($where)->order('id desc')->select();
        foreach ($list_pre as $k=>$v) {
            $list[$v['id']] = $v;
        }
        return $list;
    }
}
